package cn.rongdao.jrkabao.ui.cashadvance.manager;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;

import com.mifengkong.frtools.http.request.callback.BaseImpl;
import com.mifengkong.frtools.http.request.callback.FRBaseObserver;
import com.mifengkong.frtools.jsbridge.CallBackFunction;
import com.mifengkong.frtools.util.FRFileUtils;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.dialog.FRDialogClickListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import cn.mifengkong.appcommon.liveness.ILivenessHelper;
import cn.mifengkong.appcommon.liveness.SampleLivenessActivity;
import cn.mifengkong.appcommon.webview.InfoToJsonUtil;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.model.takephoto.KaMaoYiTuPhotoStorageModel;
import cn.rongdao.jrkabao.ui.IdentificationVerificate.IdentifySuccessEvent;
import cn.rongdao.jrkabao.ui.cashadvance.addcard.AddCreditCardForCashActivity;
import cn.rongdao.jrkabao.ui.deposit.account.MyAccountActivity;
import cn.rongdao.jrkabao.util.permission.GoToPermissionSetting;

/**
 * Created by jack on 2018/3/13
 */

public class LivenessManager {
    public static final int REQUEST_CODE_LIVENESSACTIVITY = 6;
    public static final int PERMISSION_READ_EXTERNAL_STORAGE = 101;
    public static final int PERMISSION_WRITE_EXTERNAL_STORAGE = 102;
    public static final int PERMISSION_CAMERA = 103;

    private FRDialog retryDialog;//活体检测出现错误的时候，显示这个dialog

    private String institutionId = "";
    private boolean isMyAccount;

    private Map<String, String> mUserInfoMap = new HashMap<>();

    private BaseImpl baseImpl;
    private boolean isNeedFinish;
    private CallBackFunction function;

    public LivenessManager(BaseImpl baseImpl) {
        this.baseImpl = baseImpl;
    }

    public void initLivenessDialog(final View livenessView) {
        retryDialog = new FRDialog.MDBuilder(baseImpl.getActivity())
                .setTitle("温馨提示")
                .setMessage("活体检测失败，请重试")
                .setNegativeContentAndListener("取消", null)
                .setNegativeTextColor(ContextCompat.getColor(baseImpl.getActivity(), R.color.c333333))
                .setPositiveTextColor(ContextCompat.getColor(baseImpl.getActivity(), R.color.colorPrimary))
                .setPositiveContentAndListener("重试",new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        startLivenessActiviity(livenessView);
                        return true;
                    }
                })
                .setCancelable(true)
                .setCancelableOutside(false)
                .create();
    }

    public void startLivenessActiviity(View view) {
        if (!requestPermission()) {
            if (view == null) {
                showLackPermissionDialog();
            } else {
                GoToPermissionSetting.showSnackBar(baseImpl.getActivity(), view);
            }
            return;
        }
        Intent i = new Intent(baseImpl.getActivity(), SampleLivenessActivity.class);
        baseImpl.getActivity().startActivityForResult(i, REQUEST_CODE_LIVENESSACTIVITY);
    }

    private void showLackPermissionDialog() {
        new FRDialog.MDBuilder(baseImpl.getActivity())
                .setMessage("缺少相机或者读取存储卡权限，是否去授权？")
                .setNegativeContentAndListener("否", null)
                .setNegativeTextColor(ContextCompat.getColor(baseImpl.getActivity(), R.color.c333333))
                .setPositiveTextColor(ContextCompat.getColor(baseImpl.getActivity(), R.color.colorPrimary))
                .setPositiveContentAndListener("是", new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        GoToPermissionSetting.GoToSetting(baseImpl.getActivity());
                        return true;
                    }
                })
                .show();
    }

    private boolean requestPermission() {
        if (ContextCompat.checkSelfPermission(baseImpl.getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(baseImpl.getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_WRITE_EXTERNAL_STORAGE);
            return false;
        }
        if (ContextCompat.checkSelfPermission(baseImpl.getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(baseImpl.getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_READ_EXTERNAL_STORAGE);
            return false;
        }
        if (ContextCompat.checkSelfPermission(baseImpl.getActivity(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(baseImpl.getActivity(), new String[]{Manifest.permission.CAMERA}, PERMISSION_CAMERA);
            return false;
        }

        return true;
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        try {
            switch (requestCode) {
                case PERMISSION_CAMERA: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    } else {
                        FRToast.showToastSafe("没有摄像头权限我什么都做不了哦!");
                    }
                    break;
                }
                case PERMISSION_READ_EXTERNAL_STORAGE: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    } else {
                        FRToast.showToastSafe("请打开存储读写权限，确保APP正常运行");
                    }
                    break;
                }
                case PERMISSION_WRITE_EXTERNAL_STORAGE: {
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    } else {
                        FRToast.showToastSafe("请打开存储读写权限，确保APP正常运行");
                    }
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_LIVENESSACTIVITY:
                //表示是活体检测SDK自动返回的(成功或者是失败两种情况)
                if (data == null)
                    return;
                boolean mIsSuccess = data.getBooleanExtra(ILivenessHelper.LIVENESSACTIVITYSUCCESSTAG, false);
                if (mIsSuccess) {
                    String base64Data1 = FRFileUtils.read("base64Data1");
                    judgeWhetherTheSamePerson(base64Data1);
                } else {
                    if (null != retryDialog) {
                        retryDialog.show();
                    }
                }
                break;
        }
    }

    /**
     * 依图SDK返回的照片和身份证对比，判断是否同一个人
     *
     * @param base64Data1
     */
    private void judgeWhetherTheSamePerson(String base64Data1) {
        mUserInfoMap.put("suffix", "jpeg");
        mUserInfoMap.put("query_image_1", FRString.valueOf(base64Data1));
        KaMaoYiTuPhotoStorageModel.getInstance().execute(mUserInfoMap, new FRBaseObserver<String>(baseImpl, "正在提交，请稍候...") {
            @Override
            protected void onBaseNext(String data) {
                FRToast.showToastSafe("身份信息验证成功");
                if (null != function) {
                    InfoToJsonUtil.assemblyIntoJson(function, new JSONObject());
                    return;
                }
                EventBus.getDefault().post(new IdentifySuccessEvent());
                if (isMyAccount) {
                    MyAccountActivity.start(baseImpl.getActivity());
                    baseImpl.getActivity().finish();
                    return;
                }
                if (!FRString.isEmpty(institutionId)) {
                    AddCreditCardForCashActivity.start(baseImpl.getActivity(), true, false, institutionId, false);
                    baseImpl.getActivity().finish();
                    return;
                }
                if (isNeedFinish) {
                    baseImpl.getActivity().finish();
                }
            }

            @Override
            protected void onBaseError(Throwable t) {
                super.onBaseError(t);
                if (!FRString.isEmpty(t.getMessage()) && t.getMessage().contains("比对失败")) {
                    retryDialog.show();
                    return;
                }
                if (isMyAccount) {
                    MyAccountActivity.start(baseImpl.getActivity());
                    baseImpl.getActivity().finish();
                    return;
                }
                if (!FRString.isEmpty(institutionId) && isNeedFinish) {
                    baseImpl.getActivity().finish();
                }
            }
        });
    }

    public void setNeedFinish(boolean isNeedFinish) {
        this.isNeedFinish = isNeedFinish;
    }

    public void setInstitutionId(String institutionId) {
        this.institutionId = institutionId;
    }

    public void setIsMyAccount(boolean isMyAccount) {
        this.isMyAccount = isMyAccount;
    }

    public void setStrJs(CallBackFunction function) {
        this.function = function;
    }
}